package jd.com;

import jd.util.ExcelHandle;
import org.apache.commons.collections4.map.CaseInsensitiveMap;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.usermodel.*;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.*;
import java.util.*;

/**
 * Created by wangpengzhi1 on 2018/9/19.
 */
public class ItemChangeListener implements ItemListener,ActionListener {

    private String headerTitle;
    private ArrayList<String> choseList;
    private ArrayList<String> choseList1;
    private ArrayList<String> keyList;
    private MyJDialog ui;
    private int source;

    ArrayList<Object[]> data1;
    ArrayList<Object[]> data2;

    Object[] dataCol1;
    Object[] dataCol2;

    ArrayList<ArrayList<Object>>  data;
    ArrayList<String> title;


    public ItemChangeListener( ArrayList<String> choseList,ArrayList<String> choseList1,
                               ArrayList<String> keyList, ArrayList<Object[]> list1,
                               ArrayList<Object[]> list2, MyJDialog ui,
                               Object[] dataCol1, Object[] dataCol2){
        this.choseList = choseList;
        this.choseList1 = choseList1;
        this.keyList = keyList;
        this.data1 = list1;
        this.data2 = list2;
        this.ui = ui;
        this.dataCol1 = dataCol1;
        this.dataCol2 = dataCol2;

    }
    public ItemChangeListener(String headerTitle, ArrayList<String> choseList,int source){
        this.headerTitle = headerTitle;
        this.choseList = choseList;
        this.source = source;
    }

    public ItemChangeListener(ArrayList<ArrayList<Object>>  data, ArrayList<String> title){
        this.data = data;
        this.title = title;
    }


    public void actionPerformed(ActionEvent e) {
        if(e.getActionCommand().equals("getData")){
            if(keyList.size() != 2){
                JOptionPane.showMessageDialog(ui, "请选择筛选列！");
            }
            getChoosenData();
        }
        if(e.getActionCommand().equals("importExcel")){
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            if(fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
                try {
                    createTempFile();
                    this.writeExcelByPojo(fileChooser.getSelectedFile());
                    removeTempFile();
                }catch (Exception e1){
                    e1.printStackTrace();
                }
                JOptionPane.showMessageDialog(ui, "文件导出成功！保存位置" + fileChooser.getSelectedFile().getAbsolutePath() + "\\result.xlsx");
            }
        }
    }
    public void itemStateChanged(ItemEvent e) {
        if(source == 1 || source == 2) {
            if (e.getStateChange() == 1) {
                choseList.add(headerTitle);
            } else {
                choseList.remove(headerTitle);
            }
        }else if(source == 3){
            if (e.getStateChange() == 1) {
                choseList.add(0, headerTitle);
            } else {
                choseList.remove(0);
            }
        }else if(source == 4){
            if (e.getStateChange() == 1) {
                choseList.add(1, headerTitle);
            } else {
                choseList.remove(1);
            }
        }
    }

    public void writeExcelByPojo(File sourceFileName) throws Exception{
        String tempFilePath = "D:\\temp.xlsx";
        List<String> dataListCell = new ArrayList<String>();
        for(String cellName : title){
            dataListCell.add(cellName);
        }

        List<Map<String,Object>> dataList = new ArrayList<Map<String, Object>>();
        for(int i = 0; i< data.size(); i++){
            ArrayList<Object> obj = data.get(i);
            Map<String,Object> map = new HashMap<String, Object>();
            for(int j=0; j< title.size(); j++){
                map.put(title.get(j), obj.get(j));
            }
            dataList.add(map);
        }

        ExcelHandle handle = new  ExcelHandle();
        handle.writeListData(tempFilePath, dataListCell, dataList, 0);
        OutputStream os = new FileOutputStream(sourceFileName.getAbsoluteFile() + "\\result.xlsx");
        //写到输出流并关闭资源
        handle.writeAndClose(tempFilePath, os);
        os.flush();
        os.close();
    }

    public void getChoosenData(){
        String key1 = keyList.get(0);
        String key2 = keyList.get(1);
        int index1 = getIndexByKey(key1, dataCol1);
        int index2 = getIndexByKey(key2, dataCol2);
        CaseInsensitiveMap<String, Object[]> map1= new CaseInsensitiveMap<String, Object[]>();
        CaseInsensitiveMap<String, Object[]> map2= new CaseInsensitiveMap<String, Object[]>();
        for(Object[] obj : data1){
            if(obj.length > index1){
               map1.put(obj[index1].toString(), obj);
            }
        }
        for(Object[] obj : data2){
            if(obj.length > index2) {
                map2.put(obj[index2].toString(), obj);
            }
        }
        ArrayList<ArrayList<Object>> datalist = new ArrayList<ArrayList<Object>>();
        ArrayList<String> titleObj = new ArrayList<String>();
        titleObj.addAll(choseList);
        titleObj.addAll(choseList1);
        for (String key : map1.keySet()){
            if(map2.get(key) != null){
                Object[] data1 = map1.get(key);
                Object[] data2 = map2.get(key);
                ArrayList<Object> dataObj = new ArrayList<Object>();
                for (String chooseKey : choseList){
                    dataObj.add(data1[getIndexByKey(chooseKey, dataCol1)]);
                }
                for (String chooseKey : choseList1){
                    dataObj.add(data2[getIndexByKey(chooseKey, dataCol2)]);
                }
                datalist.add(dataObj);
            }
        }
        new MyJDialog(ui, datalist, titleObj).setVisible(true);
    }

    public int getIndexByKey(String key, Object[] data){
        for (int i = 0; i < data.length; i++){
            if(data[i].toString().equals(key)){
               return i;
            }
        }
        return 0;
    }


    private void createTempFile(){
        XSSFWorkbook wb = new XSSFWorkbook();
        XSSFSheet sheet = wb.createSheet("sheet0");
        for(int i = 0; i < title.size(); i++){
            sheet.setColumnWidth(i, 20*300);
        }

        XSSFRow row = sheet.createRow(0);
        XSSFCellStyle style = wb.createCellStyle();
        style.setFillBackgroundColor(IndexedColors.BLUE.getIndex());

        for(int i = 0; i < title.size(); i++){
            XSSFCell cell = row.createCell(i);
            cell.setCellStyle(style);
            cell.setCellValue(title.get(i));
        }

        //创建HSSFRow对象
        XSSFRow row1 = sheet.createRow(1);
        for(int i=0; i<title.size(); i++){
            //创建HSSFCell对象
            XSSFCell cell = row1.createCell(i);
            cell.setCellValue("<!%"+title.get(i));
        }
        try {
            FileOutputStream output = new FileOutputStream("D:\\temp.xlsx");
            wb.write(output);
            output.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void removeTempFile(){
        File tempFile = new File("D:\\temp.xlsx");
        if(tempFile.exists()) tempFile.delete();
    }
}
